package cn.yunhe.springmvc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SpringMVCSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {  
    
    public static final Log log = LogFactory.getLog(SpringMVCSimpleMappingExceptionResolver.class);  
      
    @Override  
    protected ModelAndView doResolveException(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception ex) {  
        ModelAndView mv = null;  
        String accept = request.getHeader("accept");  
        if (accept != null && !(accept.indexOf("application/json") > -1   
                || (request.getHeader("X-Requested-With") != null   
                && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {  
            mv = super.doResolveException(request, response, handler, ex);  
        } else {  
            try {   
            	//告知浏览器编码方式
                response.setHeader("Content-type", "text/html;charset=UTF-8"); 
                //JSON请求返回  
                PrintWriter writer = response.getWriter();

                Map<String, Object> map = new HashMap<String, Object>();
				map.put("success", false);
				map.put("msg", ex.getMessage());
				ObjectMapper mapper = new ObjectMapper();
				writer.write(mapper.writeValueAsString(map));
                writer.flush();  
            } catch (IOException e) {  
                if (log.isInfoEnabled()) {  
                    log.info(e.getMessage());  
                }  
            }  
        }  
        doLog((HandlerMethod) handler, ex);  
        return mv;  
    }  
      
    /** 
     * 记录异常日志 
     *  
     * @param handler 
     * @param excetpion 
     */  
    private void doLog(HandlerMethod handler, Exception excetpion) {  
       // 异常信息日志入库  
        
    }     
}  
